<template>
	<view class="chat" @tap="InputFocus">
		<scroll-view  class="ulist" :style="{height:listHeight}" scroll-y="true" :scroll-top="scrollTop">
			<view class="uni-list msgList">
				<view class="uni-list-cell" v-for="(item,index) in msgList" :key="index" :class="{'self':item.from_id == username}">
					<image v-if="item.from_id != username" class="userLogo" :src="imgUrl" mode="scaleToFill"></image>
					<image v-if="item.from_id == username" class="userLogo" :src="selfLogo" mode="scaleToFill"></image>
					<view class="msgContent" v-if="item.msg_body.text">
						<text >{{item.msg_body.text}}</text>
					</view>
					<view class="imgbox"  v-if="item.msg_body.url">
						<image :src="item.msg_body.url" :style="{width:item.msg_body.width + 'rpx'}"   mode="widthFix"></image>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<view class="bottom" :animation="animationData">
			<view class="bottomBox">
			<!-- 	<view class="voice">
					<image src="../../static/images/voice_icon.png" mode="scaleToFill"></image>
				</view> -->
				<view class="input" :class="{'empty':msginput==''}">
					<input @focus="InputFocus"  type="text" v-model="msginput"/>
				</view>
				<view class="more">
					<image @tap.stop="openBottom" v-if="msginput == ''" src="../../static/images/add_icon.png" mode="scaleToFill"></image>
					<view class="sendBtn" v-if="msginput != '' " @tap.stop="to_send()">
						发送
					</view>
				</view>
			</view>
			<view class="moreSelect" >
				<view @tap.stop="useCarme">
					<image src="../../static/images/camer.png" mode="scaleToFill"></image>
					<view>
						拍照
					</view>
				</view>
				<view @tap.stop="usePhoto">
					<image src="../../static/images/pic.png" mode="scaleToFill"></image>
					<view>
						相册
					</view>
				</view>
			</view>
			
			
		</view>
	</view>
</template>

<script>
	var animation = uni.createAnimation({
		      duration: 500,
		      timingFunction: 'ease',
		})
	export default {
		data() {
			return {
				username: "",
				msginput:"",
				animationData: {},
				isShowBottom:false,
				target_username:"",
				target_nickname:"",
				msgList:[],
				imgUrl:"",
				selfLogo:"",
				scrollTop:0,
				listHeight:'calc(100vh - 108rpx)',
				InputBottom: 0, 
				Time_now: {
					Date: '',
					Y: '',
					M: '',
					D: '',
					h: '',
					m: '',
					s: ''
				}
			};
		},
		onLoad(e) {
			this.username = 'buyer' + uni.getStorageSync("userId")
			this.target_username = 'seller' + e.storeId;
			this.target_nickname = 'seller' + e.name;
			this.selfLogo = uni.getStorageSync('userLogo')
			uni.setNavigationBarTitle({
				title:e.name
			})
			
			this.loadNewMsg()
			
			
			
			// uni.showLoading({
			// 	title: '加载中'
			// })
			// this.Times_now();
			// this.load_chater_info()
			// this.to_bottom()
			// this.get_msg_ol()

		},
		onShow() {
			this.getCharList()
		},
		methods: {
			openBottom(){
				  this.isShowBottom = true;
				  this.animation = animation;
				  this.animation.height('370rpx').step()
				  this.listHeight = 'calc(100vh - 370rpx)'
				  this.animationData = this.animation.export()
			},
			hideBottom(){
				 this.isShowBottom = false;
				 this.listHeight = 'calc(100vh - 108rpx)'
			},
			//获取历史消息
			getCharList(){
				
				this.$jim.updateConversation({
					'appkey' : uni.getStorageSync('appkey'),
					'username' : this.username,
				})
			},
			loadNewMsg() { 
				let that = this;
				this.$jim.onMsgReceive(function(data) {
					console.log(data)
					 that.$jim.getConversation().onSuccess(function(data2) {
						 if(data2.code == 0){
							 for (let i = 0; i < data2.conversations.length; i++) {
							 	if(data2.conversations[i].username == data.messages[0].content.from_id){
									that.$jim.getResource ({
										 'media_id' : data2.conversations[i].avatar
									}).onSuccess(data3=>{
										if(that.imgUrl.length > 0){
											
										}else{
											that.imgUrl = data3.url
										}
									}).onFail(function(data) {
										   //data.code 返回码
										   //data.message 描述
									});
								}
							 }
						 }
					   }).onFail(function(data) {
						   //data.code 返回码
						   //data.message 描述
					   });
					
					if(data.messages[0].content.msg_type == 'text'){
						//文本直接添加
						that.msgList.push(data.messages[0].content);
						that.scrollTop += 90
					}else if(data.messages[0].content.msg_type == 'image'){
						
						//图片情况下处理
						that.$jim.getResource({
								 'media_id' : data.messages[0].content.msg_body.media_id,
							   }).onSuccess(function(data2) {
								   data.messages[0].content.msg_body.url = data2.url
								   let ratio = data.messages[0].content.msg_body.width / data.messages[0].content.msg_body.height
								   if (ratio < 0.4 ){
								     data.messages[0].content.msg_body.width = 204; //这是从微信截图的长度最后需要同一除以3
								     data.messages[0].content.msg_body.height = 510;
								     $img.parentElement.classList.add('overflowHeight'); //设置高度溢出部分隐藏
								   }else if(ratio >= 0.4 && ratio <= 0.5){
								     data.messages[0].content.msg_body.width = 204;
								     data.messages[0].content.msg_body.height = 204/ratio;
								   } else if(ratio > 0.5 && ratio < 1) {
								     data.messages[0].content.msg_body.width = 405 * ratio;
								     data.messages[0].content.msg_body.height = 405;
								   } else if(ratio >= 1 && ratio < 1/0.5) { //和前面的宽高转置
								     data.messages[0].content.msg_body.height = 405 * (1/ratio);
								     data.messages[0].content.msg_body.width = 405;
								   } else if (ratio >= 1/0.5 && ratio < 1/0.4) {
								     data.messages[0].content.msg_body.height = 204;
								     data.messages[0].content.msg_body.width = 204 / (1/ratio);
								   } else if (ratio >= 1/0.4) {
								     data.messages[0].content.msg_body.height = 204; //这是从微信截图的长度最后需要同一除以3
								     data.messages[0].content.msg_body.width = 510;
								     $img.parentElement.classList.add('overflowWidth');
								   }
								   // data.messages[0].content.msg_body.height /= 2;
								   // data.messages[0].content.msg_body.width /= 2;
								   that.msgList.push(data.messages[0].content);
								   that.scrollTop += data.messages[0].content.msg_body.height + '50'
								   
								   
							   }).onFail(function(data) {
								   
							   });
					}else {
						data.messages[0].content.msg_body.text = "暂不支持此类型消息，请到app端查看"
						that.msgList.push(data.messages[0].content);
					}
					
					//已读消息回执
					let msg_ids = [data.messages[0].msg_id]
					that.$jim.addSingleReceiptReport({
					  'username' : that.username,
					  'msg_ids' : msg_ids
					 }).onSuccess(function(data2,msg_ids){
					 }).onFail(function(data,msg_ids){

					 })
					  
				});
			},
			Times_now() {
				var that = this;
				var date = new Date();
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
				var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
				var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + '';
				var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
				// console.log(date)
				that.$data.Time_now.Date = date;
				that.$data.Time_now.Y = Y;
				that.$data.Time_now.M = M;
				that.$data.Time_now.D = D;
				that.$data.Time_now.h = h;
				that.$data.Time_now.m = m;
				that.$data.Time_now.s = s;
			},
			get_message_time(timestamp, msg_ids) {
				let that = this;
				let Time_now = that.$data.Time_now;

				var date = new Date(timestamp);
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
				var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
				var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + '';
				var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
				if (Y == Time_now.Y && M == Time_now.M && D == Time_now.D) {
					that.$data.Chat_Record[msg_ids].timess = h + m;
				} else {
					that.$data.Chat_Record[msg_ids].timess = M + D;
				}
				// return Y + M + D + h + m + s;
			},
			//发送消息
			to_send() {
				var that = this;
				this.$jim.sendSingleMsg({
					'target_username': that.target_username,
					'target_nickname': that.target_nickname,
					'content': this.msginput,
					'appkey': '3c2538a2a88d830992a411b4'
				}).onSuccess(function(data, msg) {
					if (data.code == 0) {
						//发送成功了
						// that.Times_now();
						// msg.content.timess = that.$data.Time_now.h + that.$data.Time_now.m
						that.msgList.push(msg.content)
						that.scrollTop += 90
						that.msginput = ''
					} else {
						uni.showToast({
							title: '发送失败'
						})
					}
				}).onFail(function(data) {
					//data.code 返回码
					//data.message 描述
				});
			},
		

			//编辑框事件
			InputFocus(e) {
				// // #ifdef MP-WEIXIN
				// 	uni.onKeyboardHeightChange(res => {
				// 	  if(res.height == 0){
				// 		  this.animation.height('108rpx').step({duration: 0})
				// 		  this.listHeight = 'calc(100vh - 370rpx)'
				// 		  this.animationData = this.animation.export()
				// 	  }else{
				// 		this.listHeight = 'calc(100vh - 370rpx)'
				// 	  }
				// 	})
				// // #endif
				
				if(this.isShowBottom == true){
					  // this.animation.height('108rpx').step({duration: 0})
					  this.animation.height('108rpx').step()
					  this.listHeight = 'calc(100vh - 108rpx)'
					  this.animationData = this.animation.export()
					  this.isShowBottom = false
				}else{
					this.listHeight = 'calc(100vh - 108rpx)'
				}	
				 
			},
			InputBlur(e) {
				console.log(1)
				this.InputBottom = 0;
				this.listHeight = 'calc(100vh - 108rpx)'
			},
			useCarme(){
				var that = this;
				uni.chooseImage({
				    count: 9, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['camera'], //从相册选择
				    success: function (res) {
						var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径
					  that.$jim.sendSinglePic({
						 'target_username': that.target_username,
						 'target_nickname': that.target_nickname,
						 'appkey': '3c2538a2a88d830992a411b4',
						 'image' : tempFilePaths //设置图片参数
						  }).onSuccess(function(data,msg) {
							  console.log(msg)
							 that.$jim.getResource({
							 		 'media_id' : msg.content.msg_body.media_id,
							 	   }).onSuccess(function(data2) {
							 		   msg.content.msg_body.url = data2.url
							 		   console.log(data)
							 		   let ratio = msg.content.msg_body.width / msg.content.msg_body.height
							 		   if (ratio < 0.4 ){
							 		     msg.content.msg_body.width = 204; //这是从微信截图的长度最后需要同一除以3
							 		     msg.content.msg_body.height = 510;
							 		   }else if(ratio >= 0.4 && ratio <= 0.5){
							 		     msg.content.msg_body.width = 204;
							 		     msg.content.msg_body.height = 204/ratio;
							 		   } else if(ratio > 0.5 && ratio < 1) {
							 		     msg.content.msg_body.width = 405 * ratio;
							 		     msg.content.msg_body.height = 405;
							 		   } else if(ratio >= 1 && ratio < 1/0.5) { //和前面的宽高转置
							 		     if(msg.content.msg_body.height > 200 && msg.content.msg_body.width >200){
											 msg.content.msg_body.height = 405 * (1/ratio);
											 msg.content.msg_body.width = 405;
										 }
							 		   } else if (ratio >= 1/0.5 && ratio < 1/0.4) {
							 		     msg.content.msg_body.height = 204;
							 		     msg.content.msg_body.width = 204 / (1/ratio);
							 		   } else if (ratio >= 1/0.4) {
							 		     msg.content.msg_body.height = 204; //这是从微信截图的长度最后需要同一除以3
							 		     msg.content.msg_body.width = 510;
							 		   }
							 		   // msg.content.msg_body.height /= 2;
							 		   // msg.content.msg_body.width /= 2;
							 		   that.msgList.push(msg.content);
							 		   that.scrollTop += msg.content.msg_body.height + '50'
							 		   
							 		   
							 	   }).onFail(function(data) {
							 		   
							 	   });
						  }).onFail(function(data) {
						   });
				    }
				});
			},
			usePhoto(){
				var that = this;
				uni.chooseImage({
				    count: 9, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['album'], //从相册选择
				    success: function (res) {
						var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径
					  that.$jim.sendSinglePic({
						 'target_username': that.target_username,
						 'target_nickname': that.target_nickname,
						 'appkey': '3c2538a2a88d830992a411b4',
						 'image' : tempFilePaths //设置图片参数
						  }).onSuccess(function(data,msg) {
							  console.log(msg)
							 that.$jim.getResource({
							 		 'media_id' : msg.content.msg_body.media_id,
							 	   }).onSuccess(function(data2) {
							 		   msg.content.msg_body.url = data2.url
							 		   console.log(data)
							 		   let ratio = msg.content.msg_body.width / msg.content.msg_body.height
							 		   if (ratio < 0.4 ){
							 		     msg.content.msg_body.width = 204; //这是从微信截图的长度最后需要同一除以3
							 		     msg.content.msg_body.height = 510;
							 		   }else if(ratio >= 0.4 && ratio <= 0.5){
							 		     msg.content.msg_body.width = 204;
							 		     msg.content.msg_body.height = 204/ratio;
							 		   } else if(ratio > 0.5 && ratio < 1) {
							 		     msg.content.msg_body.width = 405 * ratio;
							 		     msg.content.msg_body.height = 405;
							 		   } else if(ratio >= 1 && ratio < 1/0.5) { //和前面的宽高转置
							 		     if(msg.content.msg_body.height > 200 && msg.content.msg_body.width >200){
											 msg.content.msg_body.height = 405 * (1/ratio);
											 msg.content.msg_body.width = 405;
										 }
							 		   } else if (ratio >= 1/0.5 && ratio < 1/0.4) {
							 		     msg.content.msg_body.height = 204;
							 		     msg.content.msg_body.width = 204 / (1/ratio);
							 		   } else if (ratio >= 1/0.4) {
							 		     msg.content.msg_body.height = 204; //这是从微信截图的长度最后需要同一除以3
							 		     msg.content.msg_body.width = 510;
							 		   }
									   console.log(msg.content)
							 		   // msg.content.msg_body.height /= 2;
							 		   // msg.content.msg_body.width /= 2;
							 		   that.msgList.push(msg.content);
							 		   that.scrollTop += msg.content.msg_body.height + 100
									   console.log(that.scrollTop)
									   console.log(msg.content.msg_body.height);
							 		   
							 		   
							 	   }).onFail(function(data) {
							 		   
							 	   });
						  }).onFail(function(data) {
						   });
				    }
				});
			},
		}
	}
</script>

<style lang="scss">
	.chat{
		background-color: #F0F0F0;
		min-height: 100vh;
		box-sizing: border-box;
		
		.msgList{
			padding: 20upx;
			box-sizing: border-box;
			.uni-list-cell{
				display: flex;
				justify-content: flex-start;
				width: 100%;
				margin-bottom: 50upx;
				.userLogo{
					width: 80upx;
					height: 80upx;
					margin-right: 20upx;
					border-radius: 50%;
				}
				&.self{
					flex-direction:row-reverse;
					.userLogo{
						margin-left: 20upx;
						margin-right: 0;
					}
				}
				.msgContent{
					background-color: #fff;
					border-radius: 40upx;
					padding: 25upx 40upx;
					max-width: 60%;
					word-break: break-word;
				}
				.imgbox{
					max-width: 50%;
					image{
						// width: 300upx;
						height: 200upx;
					}
				}
			}
		}
		.bottom{
			position: fixed;
			bottom: 0;
			height: 108upx;
			overflow: hidden;
			
			background-color: #fff;
			width: 100%;
			.bottomBox{
				height: 108upx;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 28upx;
				box-sizing: border-box;
				image{
					width: 55upx;
					height: 55upx;
				}
				.input{
					width: 545upx;
					&.empty{
						width: 620upx;
					}
					input{
						width: 100%;
						height: 73upx;
						background-color: #f5f5f5;
						border-radius: 36upx;
						padding:0 20upx;
						font-size: 24upx;
						box-sizing: border-box;
						box-sizing: border-box;
					}
				}
				.more{
					.sendBtn{
						background-color: #F73811;
						color: #fff;
						width: 130upx;
						line-height: 70upx;
						background:linear-gradient(0deg,rgba(232,39,27,1) 0%,rgba(250,94,52,1) 100%);
						border-radius:36upx;
						text-align: center;
					}
				}
			}
			.moreSelect{
				
				height: 262upx;
				background-color: #fff;
				display: flex;
				padding: 50upx 70upx;
				// box-sizing: border-box;
				border-top: 1upx solid #f2f2f2;
				&>view{
					text-align: center;
					width: 126upx;
					height: 126upx;
					font-size: 24upx;
					color: #4d4d4d;
					margin-right: 40upx;
					image{
						width: 126upx;
						height: 126upx;
					}
				}
			}
			
		}
	}
</style>
